package proto3;

import com.example.proto3.Address;
import com.example.proto3.Contacts;
import com.example.proto3.PeopleInfo;
import com.example.proto3.Phone;
import com.google.protobuf.InvalidProtocolBufferException;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;

/**
 * 读取文件中联系人信息
 */
public class TestRead {
    public static void main(String[] args) throws IOException {
        // 1. 读取文件
        Contacts contacts = Contacts.parseFrom(
                new FileInputStream(TestWrite.CONTACTS_PATH));

        // 2.打印通讯录信息
        printContacts(contacts);

    }

    private static void printContacts(Contacts contacts) throws InvalidProtocolBufferException {
        int i = 1;
        for (PeopleInfo peopleInfo : contacts.getInfosList()) {
            System.out.println("-----------联系人" + i++ + "--------------");
            System.out.println("姓名：" + peopleInfo.getName());
            System.out.println("年龄：" + peopleInfo.getAge());
            int j = 1;
            for (Phone phone : peopleInfo.getPhoneList()) {
                System.out.println("电话" + j++ + ": " + phone.getNumber()
                        + "   (" + phone.getType().name() + ")");
            }
            if (peopleInfo.hasData()
                    && peopleInfo.getData().is(Address.class)) {
                // any -> Address
                Address address = peopleInfo.getData().unpack(Address.class);
                if (!address.getHomeAddress().isEmpty()) {
                    System.out.println("家庭地址：" + address.getHomeAddress());
                }
                if (!address.getUnitAddress().isEmpty()) {
                    System.out.println("单位地址：" + address.getUnitAddress());
                }
            }

            switch (peopleInfo.getOtherContactCase()) {
                case QQ:
                    System.out.println("qq号：" + peopleInfo.getQq());
                    break;
                case WECHAT:
                    System.out.println("微信号：" + peopleInfo.getWechat());
                    break;
                case OTHERCONTACT_NOT_SET:
                    break;
            }

            for (Map.Entry<String, String> entry : peopleInfo.getRemarkMap().entrySet()) {
                System.out.println("   " + entry.getKey() + ": " + entry.getValue());
            }
        }
    }
}
